package com.bdqn.easybuy1.dao.impl;

import com.bdqn.easybuy1.dao.BaseDao;
import com.bdqn.easybuy1.dao.UserAddressDao;
import com.bdqn.easybuy1.entities.UserAddress;
import com.bdqn.easybuy1.param.UserAddressParam;
import com.bdqn.easybuy1.utils.EmptyUtils;

import java.sql.Connection;
import java.util.ArrayList;
import java.util.List;

public class UserAddressDaoImpl extends BaseDao<UserAddress> implements UserAddressDao {

    /**
     * 查询用户所有的地址列表
     *
     * @param conn  数据库连接对象
     * @param param 查询参数
     * @return 返回地址对象列表
     */
    @Override
    public List<UserAddress> queryUserAddressList(Connection conn, UserAddressParam param) {
        String sql = " SELECT `id`,`userId`,`address`,`createTime`,`isDefault`,`remark` FROM `easybuy_user_address`  WHERE 1 = 1 ";

        List<Object> objParams = new ArrayList<>();

        StringBuilder sb = new StringBuilder(sql);

        if (EmptyUtils.isNotEmpty(param.getUserId())) {
            sb.append(" AND `userId` = ? ");
            objParams.add(param.getUserId());
        }

        if (EmptyUtils.isNotEmpty(param.getAddress())) {
            sb.append(" AND `address` LIKE ?");
            objParams.add("%" + param.getAddress() + "%");
        }

        if (EmptyUtils.isNotEmpty(param.getSort())) {
            sb.append(" ORDER BY " + param.getSort());
        }

        if (param.isPage()) {
            sb.append(" LIMIT " + param.getStartIndex() + "," + param.getPageSize());
        }

        return getBeanList(conn, sb.toString(), objParams.toArray());
    }

    /**
     * 往数据库中插入一条用户地址信息
     *
     * @param conn        数据库连接对象
     * @param userAddress 封装地址数据对象
     * @return 返回受影响的行数
     */
    @Override
    public int insert(Connection conn, UserAddress userAddress) {
        String sql = "INSERT INTO `easybuy_user_address`(`userId`,`address`,`createTime`,`isDefault`,`remark`) VALUES(?,?,?,?,?)";
        Long keyId = super.insert(conn, sql,
                userAddress.getUserId(),
                userAddress.getAddress(),
                userAddress.getCreateTime(),
                userAddress.getIsDefault(), // 表示是否是默认地址
                userAddress.getRemark());

        userAddress.setId(keyId.intValue());

        return 1;
    }

    /**
     * 根据地址的id获取地址信息对象
     *
     * @param conn      数据库连接对象
     * @param addressId 地址id
     * @return 返回地址信息对象
     */
    @Override
    public UserAddress getUserAddressById(Connection conn, Integer addressId) {
        String sql = "SELECT `id`,`userId`,`address`,`createTime`,`isDefault`,`remark` FROM `easybuy_user_address`  WHERE `id` = ?";
        return getBean(conn, sql, addressId);
    }
}
